<?php

namespace App\Services\Cache;


use App\Models\GroupProduct;
use Illuminate\Support\Facades\Cache;
use Carbon\Carbon;
use App\Models\Order;

class BrokerageCache
{
	public function count()
	{
		$user = request()->user();
		$key = "user-{$user->id}-brokerage";
		$count = Cache::remember($key, 1, function () use ($user) {
			
			$brokerageAccounter = account_brokerages($user);
			$child = $user->children()->get();	
			$ids = [];
			if($child){

				$ids = array_column($child->toArray(),'id');
			}

			$dayOrderMoney = 0;
			$dayOrderCount = 0;
			$monthOrderMoney = 0;
			$monthOrderCount = 0;
			if($ids){
				$dayOrder = Order::where('user_id',$ids)->whereNotNull('paid_at')->whereDate('created_at', Carbon::today());
				$dayOrderMoney = $dayOrder->sum('total_amount');
				$dayOrderCount = $dayOrder->count();
				$monthOrder = Order::where('user_id',$ids)->whereNotNull('paid_at')->whereYear('created_at', Carbon::today()->year)
            ->whereMonth('created_at', Carbon::today()->month);
				$monthOrderMoney = $monthOrder->sum('total_amount');
				$monthOrderCount = $monthOrder->count();
			}
			

			$count = [];
			$count['user_id'] = $user->id;
			$count['day_brokerage'] = $brokerageAccounter->dayBrokerage()->sum('money');
			$count['day_order_money'] = $dayOrderMoney;
			$count['day_order_count'] = $dayOrderCount;
			$count['month_brokerage'] = $brokerageAccounter->monthBrokerage()->sum('money');
			$count['month_order_money'] = $monthOrderMoney;
			$count['month_order_count'] = $monthOrderCount;
			$count['last_month_brokerage'] = $brokerageAccounter->lastMonthBrokerage()->sum('money');
			$count['all_brokerage'] = $brokerageAccounter->allBrokerage()->sum('money');
			
			return $count;
		});
		return $count;
	}
	
	
}
